package softswitch.ws;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import softswitch.model.CallDetail;
import softswitch.model.Circuit;
import softswitch.model.Offer;
import softswitch.model.OfferDetail;
import softswitch.model.Package;
import softswitch.model.Plan;
import softswitch.model.PlanDetail;
import softswitch.model.Route;
import softswitch.model.RoutePrefix;
import softswitch.service.RouteService;
import util.DateUtil;


@Stateless
public class AgiProcessService {
	
	@EJB
	SoftswitchService softswitchService;
	
	@EJB
	RouteService routeService;

	DateUtil  dateUtil = new DateUtil();
	CallLogger callLogger = new CallLogger();
	
	
	public Boolean processCallResult(String dialstatus, String dialedtime, String answeredtime) {
		
		if( dialstatus != null ) {
			
			if(dialstatus.equals("ANSWER")){
			
				Integer time = 0;
				if( dialedtime != null ) {
					if( dialedtime.equals("") ) {
						time = Integer.parseInt(dialedtime);
					}
				}
				
				Integer billsec = 0;
				if( answeredtime != null ) {
					if( answeredtime.equals("") ) {
						billsec = Integer.parseInt(answeredtime);
					}
				}
				
				Date start = new Date();
				Date end = new Date();
				Date answer = null;
				
				answer = dateUtil.addSeconds(start , time - billsec );
				
				//cdr.setBilled(true);
				//cdr.setBillsec(billsec);
				//cdr.setDisposition(dialstatus);
				//cdr.setDcontext("outbound");
				//cdr.setAnswer(answer);
				
				System.out.println("ESTATUS "+dialstatus);
					
				//CallDetail calldetail = callProcessorService.billCDR(cdr);
				//if(calldetail!=null){
					//System.out.println("UPDATING SUMMARIES");
					//callProcessorService.updatePackageSummary(calldetail);
					//callProcessorService.updateCallSummaryRouteGroup(calldetail);
					//callProcessorService.updateCallSummaryMonth(calldetail);
				//}
				
			}	
			
		}
			
		return true;
		
	}
			
	public String validateCallerId(String callerid) {
		String result = "15005050";
		return result;
	}

	public Boolean hasValidCircuit(String accountcode,CallDetail calldetail) {
		Boolean result = false;
		if(accountcode == null) {
			callLogger.calllog(calldetail, "DEBUG", "CallProcess", "This Call Dont have accountcode");
		}
		else{			
			Long circuitcode = Long.parseLong(accountcode);
			Circuit circuit = softswitchService.getCircuitByCode(circuitcode);
			if(circuit == null) {
				callLogger.calllog(calldetail, "DEBUG", "CallProcess", "This Call Dont have Circuit");
			}
			else{
				calldetail.setCircuit(circuit);
				result = true;
			}
		}
		return result;
	}
	
	public Boolean hasValidPlan(String destination,CallDetail calldetail) {
		Boolean result = false;
		
		RoutePrefix routeprefix = softswitchService.getRoutePrefixByDestination(destination);						
		if(routeprefix==null){
			callLogger.calllog(calldetail, "DEBUG", "CallProcess", "No Route to Destination " + destination);
		}
		else{
			
			Route route = routeService.getById(routeprefix.getRoute().getId());
			Circuit circuit = softswitchService.getCircuitById(calldetail.getCircuit().getId());
			Plan plan = softswitchService.getPlanById(circuit.getPlan().getId());
			PlanDetail plandetail = softswitchService.getPlanDetailByPlanRoute(plan, routeprefix.getRoute());							
			if(plandetail == null){
				callLogger.calllog(calldetail, "ERROR","CallProcess", "No PlanDetail for Route" + route.getName() + " Destination " + destination);

			}
			else{
				callLogger.calllog(calldetail, "DEBUG","CallProcess", "Route Found: " + route.getName() );

				calldetail.setRoute(route);
				result = true;
			}
				
		}

		return result;
		
	}
	
	//Return null = No Package Found
	//Return 1 = Package Found With Credit
	//Return 2 = Package Found With Full Credit
	//Return 3 = Package Found With Full Credit With ExtraCredit
	public Integer checkPackageStatus(CallDetail calldetail) {
		
		Integer result = null;
		
		List<Package> packags = softswitchService.listPackagesByCircuit(calldetail.getCircuit());
		if(packags == null || packags.isEmpty()){
			callLogger.calllog(calldetail, "ERROR", "CallProcess", "No Packages Found");
		}
		else{
			
			Iterator<Package> packagsIt = packags.iterator();
			
			while(packagsIt.hasNext()){
				
				Package packag = packagsIt.next();
				
				Offer offer = packag.getOffer();
				
				OfferDetail oferdetail = softswitchService.getOfferDetailByOfferRoute(offer,calldetail.getRoute());
				
				if(oferdetail != null){
					callLogger.calllog(calldetail, "DEBUG", "CallProcess", "Package Found: " + packag.getOffer().getName() );
					
					Double monthlyMinutes = packag.getOffer().getMinutes();
					
					callLogger.calllog(calldetail, "DEBUG", "CallProcess", "Package Monthly Minutes: " + monthlyMinutes);

					//Date date = calldetail.getCalldate();
					Date date = null;
					
					Date startofmonth = dateUtil.firstTimeOfMonth(date);
					Date endofmonth = dateUtil.lastTimeOfMonth(date);
					
					//Long totalExpLong = softswitchService.getPackageSummaryTotalTime(year, month, day, packag);
					Long totalExpLong = null;
					
					Integer totalExpended = 0;
				
					if(totalExpLong != null){
						callLogger.calllog(calldetail, "DEBUG", "calldetailJOB", "Package Minutes Used: " + totalExpLong/60);
						totalExpended = totalExpLong.intValue();
					}
					
					if(totalExpended.doubleValue() < monthlyMinutes){
						result = 1;
					}
					else{
						
						//if(packag.getContinue2plan()==true){
							//callLogger.calllog(calldetail, "DEBUG", "CallProcess", "Free Minutes Used but Continue to Plan is Enable");
							//result = 3;
						//}
						//else{
							//callLogger.calllog(calldetail, "ERROR", "CallProcess", "Free Minutes Used / This call dont have credit for this Route");
							//result = 2;
						//}

					}	
					break;
				}
				
			}//while	
		
		}//else
		
		return result;
		

	}//checkPackageStatus()
	
	
	public CallDetail process(CallDetail calldetail) { 
		
		/*
		String accountcode = cdr.getAccountcode();
		
		String destination = cdr.getDst();
		String uniqueid = cdr.getUniqueid();
		String dcontext = cdr.getDcontext();
		String disposition = cdr.getDisposition();
		Integer billsec = cdr.getBillsec();
		Date calldate = cdr.getAnswer();
		
				
		if(! ( disposition.equals("ANSWERED") || disposition.equals("ANSWER") ) ){
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Process No Complete Call");
			softswitchService.setCdr2Billed(uniqueid,true);
			return null;
		}
		
		if(billsec == 0){
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Call With Zero Time");
			softswitchService.setCdr2Billed(uniqueid,true);
			return null;
		}
		
		if(accountcode == null) {
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "This CDR dont have accountcode");
			softswitchService.setCdr2Billed(uniqueid,true);
			return null;
		}
		
		if(accountcode.equals("")) {
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "This CDR dont have accountcode");
			softswitchService.setCdr2Billed(uniqueid,true);
			return null;
		}
		
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Processing CDR");
		
		if(dcontext.equals("inbound")) {
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Process Inbound Call");
			softswitchService.setCdr2Billed(uniqueid,true);
			return null;
		}
		
		Long circuitcode = Long.parseLong(accountcode);
		Circuit circuit = softswitchService.getCircuitByCode(circuitcode);
		if(circuit==null){
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "No Circuit Code Found "+ circuitcode);
			softswitchService.setCdr2Billed(uniqueid,false);
			return null;
		}
		
		Organization organization = softswitchService.getOrganizationById(circuit.getOrganization_id());
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Circuit "+circuitcode+" "+organization.getName());
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "ID " + uniqueid);
		
		RoutePrefix routeprefix = softswitchService.getRoutePrefixByDestination(destination);
		if(routeprefix==null){
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "No Route for destination " + destination);
			softswitchService.setCdr2Billed(uniqueid,false);
			return null;
		}
		
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "This Call has a Route and Prefix");
		
	
		Plan plan = softswitchService.getPlanById(circuit.getPlan_id());
		PlanDetail plandetail = softswitchService.getPlanDetailByPlanRoute(plan, routeprefix.getRoute_id());							
		if(plandetail == null){
			callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "No PlanDetail for Destination " + destination);
			softswitchService.setCdr2Billed(uniqueid,false);
			return null;
		}
		
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "This Call has a valid Plan");
		
		Integer block = plandetail.getBlock();
		
		Integer chunk = 0;
		if(billsec <= block){
			chunk = 1;
		}
		else{
			chunk = (int) Math.ceil(billsec/block);
		}
		Integer seconds = chunk * block;		
		Double minutes = seconds.doubleValue()/60;
		
		Double rate = plandetail.getRate();
		rate = Math.round( rate * 1000.0 ) / 1000.0;
		
		Double cost = rate * minutes;
		cost = Math.round( cost * 10000.0 ) / 10000.0;
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Time in Seconds  " + billsec);
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Billing Block  " + block);
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Billing Chunk  " + chunk);
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Rate Per Minute  " + rate);
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Rounded Time in Seconds  " + seconds);
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Time in Minutes  " + minutes);
		callLogger.calllog(cdr, "DEBUG", "calldetailJOB", "Price to Bill  " + cost);
		
		CallDetail callDetail = new CallDetail();
		callDetail.setCalldate(calldate);
		callDetail.setUniqueid(cdr.getUniqueid());
		callDetail.setSource(cdr.getSrc());
		callDetail.setDestination(cdr.getDst());
		callDetail.setCallerid(cdr.getClid());
		callDetail.setDisposition(cdr.getDisposition());
		callDetail.setTime(seconds);
		callDetail.setRate(rate);
		callDetail.setCost(cost);
		callDetail.setCircuit_id(circuit.getId());
		callDetail.setRoute_id(routeprefix.getRoute_id());
		
		callDetail = softswitchService.saveCallDetail(callDetail);	
		
		softswitchService.setCdr2Billed(uniqueid,true);
		
		return callDetail;
		 
		*/
		
		return null;
		
	}//processCDR()


}
